package com.common.service;

import com.common.constants.Code;
import com.common.constants.Constant;
import com.common.constants.ImageType;
import com.common.exception.BusinessException;
import com.common.exception.code.BaseResponseCode;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务
 */
@Service
public class ValidateCodeService {

    @Autowired
    private RedisService redisService;

    /*
    通过sessionId存储在redis中
    当刷新验证码的时候，会将redis中原先的数据覆盖
     */
    public void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String key = session.getId();
        setHeader(response, Code.type);

        Captcha captcha = createCaptcha();
        redisService.set(Code.CODE_PREFIX  + key, StringUtils.lowerCase(captcha.text()), Code.time, TimeUnit.SECONDS);
        captcha.out(response.getOutputStream());
    }

    public void check(String key, String value) throws BusinessException {
        Object codeInRedis = redisService.get(Code.CODE_PREFIX + key);
        if (StringUtils.isBlank(value)) {
            throw new BusinessException(BaseResponseCode.CODE_NULL);
        }
        if (codeInRedis == null) {
            throw new BusinessException(BaseResponseCode.CODE_EXPIRE);
        }
        if (!StringUtils.equalsIgnoreCase(value, String.valueOf(codeInRedis))) {
            throw new BusinessException(BaseResponseCode.CODE_ERROR);
        }
    }

    private Captcha createCaptcha() {
        Captcha captcha = null;
        if (StringUtils.equalsIgnoreCase(Code.type, ImageType.GIF)) {
            captcha = new GifCaptcha(Code.width, Code.height, Code.length);
        } else {
            captcha = new SpecCaptcha(Code.width, Code.height, Code.length);
        }
        captcha.setCharType(Code.charType);
        return captcha;
    }

    private void setHeader(HttpServletResponse response, String type) {
        if (StringUtils.equalsIgnoreCase(type, ImageType.GIF)) {
            response.setContentType(MediaType.IMAGE_GIF_VALUE);
        } else {
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
        }
        response.setHeader(HttpHeaders.PRAGMA, "No-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);
    }

}
